import 'package:dio/dio.dart';
import 'app_exception.dart';

class ErrorHandler {
  /// 将 DioException 转换为 AppException
  static AppException handleDioError(DioException error) {
    switch (error.type) {
      case DioExceptionType.connectionTimeout:
      case DioExceptionType.sendTimeout:
      case DioExceptionType.receiveTimeout:
        return NetworkException('连接超时，请检查网络', error.response?.statusCode);

      case DioExceptionType.badResponse:
        return _handleResponseError(error);

      case DioExceptionType.cancel:
        return AppException('请求已取消');

      case DioExceptionType.connectionError:
        return NetworkException('网络连接失败，请检查网络设置');

      case DioExceptionType.badCertificate:
        return NetworkException('证书验证失败');

      case DioExceptionType.unknown:
        return NetworkException('未知网络错误: ${error.message}');
    }
  }

  /// 处理 HTTP 响应错误
  static AppException _handleResponseError(DioException error) {
    final statusCode = error.response?.statusCode;
    final message = error.response?.data?['message'] ?? error.message ?? '请求失败';

    switch (statusCode) {
      case 400:
        return ValidationException(message, statusCode);
      case 401:
        return AuthException('未授权，请重新登录', statusCode);
      case 403:
        return AuthException('没有权限访问', statusCode);
      case 404:
        return AppException('请求的资源不存在', statusCode);
      case 500:
      case 502:
      case 503:
        return AppException('服务器错误，请稍后重试', statusCode);
      default:
        return AppException(message, statusCode);
    }
  }

  /// 获取用户友好的错误消息
  static String getErrorMessage(dynamic error) {
    if (error is AppException) {
      return error.message;
    } else if (error is DioException) {
      return handleDioError(error).message;
    } else if (error is Exception) {
      return error.toString();
    } else {
      return '发生未知错误';
    }
  }

  /// 判断是否为网络错误
  static bool isNetworkError(dynamic error) {
    return error is NetworkException ||
        (error is DioException &&
            (error.type == DioExceptionType.connectionTimeout ||
                error.type == DioExceptionType.sendTimeout ||
                error.type == DioExceptionType.receiveTimeout ||
                error.type == DioExceptionType.connectionError));
  }

  /// 判断是否为认证错误
  static bool isAuthError(dynamic error) {
    return error is AuthException ||
        (error is DioException && error.response?.statusCode == 401);
  }

  /// 判断错误是否可重试
  static bool isRetryable(dynamic error) {
    if (error is NetworkException) {
      return true;
    }
    if (error is DioException) {
      return error.type == DioExceptionType.connectionTimeout ||
          error.type == DioExceptionType.sendTimeout ||
          error.type == DioExceptionType.receiveTimeout ||
          error.type == DioExceptionType.connectionError ||
          (error.response?.statusCode != null &&
              error.response!.statusCode! >= 500);
    }
    return false;
  }
}

